package com.spring.security.core.validate.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.spring.security.core.properties.SecurityConstants;
import com.spring.security.core.validate.*;
import com.spring.security.core.validate.exception.ValidateCodeException;
import com.spring.security.core.properties.SecurityProperties;
import com.spring.security.core.validate.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.io.IOException;
import java.util.Map;

/**
 * 验证码处理器抽象类
 *
 * @author seabed_moon
 */
public abstract class AbstractValidateCodeProcessor<C extends ValidateCode> implements ValidateCodeProcessor {

    /**
     * 收集系统中所有的 {@link ValidateCodeGenerator} 接口的实现。
     */
    @Autowired
    private Map<String, ValidateCodeGenerator> validateCodeGenerators;

    @Autowired
    private ValidateCodeRepository validateCodeRepository;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * (non-Javadoc)
     *
     * @see ValidateCodeProcessor
     * springframework.web.context.request.ServletWebRequest)
     */
    @Override
    public void create(ServletWebRequest request) throws Exception {
        C validateCode = generate(request);
        save(request, validateCode);
        send(request, validateCode);
    }

    /**
     * 生成校验码
     *
     * @param request
     * @return
     */
    private C generate(ServletWebRequest request) throws ServletRequestBindingException, IOException {
        //根据请求的url获取校验码的类型
        ValidateCodeType codeType = getValidateCodeType();
        String type = codeType.toString().toLowerCase();
        String generatorName = type + ValidateCodeGenerator.class.getSimpleName();
        ValidateCodeGenerator validateCodeGenerator = validateCodeGenerators.get(generatorName);
        if (validateCodeGenerator == null) {
            throw new ValidateCodeException("验证码生成器" + generatorName + "不存在");
        }
        if (codeType.equals(ValidateCodeType.SMS) && securityProperties.getCode().getSms().isRepeat()) {
            //根据请求的url获取校验码的类型
            C codeInSession = (C) validateCodeRepository.get(request, codeType);
            if (null != codeInSession) {
                return codeInSession;
            }
        }
        return (C) validateCodeGenerator.generate(request);
    }

    /**
     * 保存校验码
     *
     * @param request
     * @param validateCode
     */
    private void save(ServletWebRequest request, C validateCode) throws JsonProcessingException {
        //根据请求的url获取校验码的类型
        ValidateCodeType codeType = getValidateCodeType();
        ValidateCode code;
        if (codeType.equals(ValidateCodeType.SMS)) {
            code = new ValidateCode(validateCode.getMobile(), validateCode.getCode(), validateCode.surplusSecond().intValue());
        } else if (codeType.equals(ValidateCodeType.IMAGE)) {
            code = new ValidateCode(validateCode.getCode(), validateCode.getExpireTime());
        } else {
            throw new ValidateCodeException("获取校验码的类型失败");
        }

        validateCodeRepository.save(request, code, getValidateCodeType());
    }

    /**
     * 发送校验码，由子类实现
     *
     * @param request
     * @param validateCode
     * @throws Exception
     */
    protected abstract void send(ServletWebRequest request, C validateCode) throws Exception;

    /**
     * 根据请求的url获取校验码的类型
     *
     * @param
     * @return
     */
    private ValidateCodeType getValidateCodeType() {
        String type = StringUtils.substringBefore(getClass().getSimpleName(), "CodeProcessor");
        return ValidateCodeType.valueOf(type.toUpperCase());
    }

    /**
     * 验证码统一校验逻辑
     *
     * @param request
     */
    @Override
    public void validate(ServletWebRequest request) throws IOException {
        //根据请求的url获取校验码的类型
        ValidateCodeType codeType = getValidateCodeType();

        C codeInSession = (C) validateCodeRepository.get(request, codeType);

        String codeInRequest;
        try {
            codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),
                    codeType.getParamNameOnValidate());
        } catch (ServletRequestBindingException e) {
            throw new ValidateCodeException("获取验证码的值失败");
        }

        if (StringUtils.isBlank(codeInRequest)) {

            throw new ValidateCodeException(codeType + "验证码的值不能为空");
        }

        if (codeInSession == null) {
            throw new ValidateCodeException(codeType + "验证码不存在", 1001);
        }

        if (codeInSession.isExpire()) {
            validateCodeRepository.remove(request, codeType);
            throw new ValidateCodeException(codeType + "验证码已过期", 1002);
        }

        if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException(codeType + "验证码不匹配", 1003);
        }

        validateCodeRepository.remove(request, codeType);
        if (codeType.equals(ValidateCodeType.SMS)) {
            redisTemplate.delete(SecurityConstants.SMS_CODE_SEND_CHECK_KEY + codeInSession.getMobile());
        }
    }
}
